package com.huaqin.obeacons;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import com.huaqin.obeacons.bmob.Users;
import com.huaqin.obeacons.utils.HttpClientUtil;
import com.huaqin.obeacons.utils.MyDatabaseUtil;
import com.huaqin.obeacons.utils.SharedPreferenceUtil;
import com.umeng.message.PushAgent;

/**
 * @author xiabing 登录界面 url : http://www.codenow.cn/app/browser/29839 account:
 *         xiabing082@163.com/huaqin123
 */
public class LoginActivity extends Activity {
	private EditText edittext1;
	private EditText edittext2;
	private ProgressDialog mDialog;
	private String account = null;
	private String name = null;
	private String imeis = null;
	private Context mContext;
	boolean flagtest = true;
	private MyDatabaseUtil dbhelper;
	boolean flagimei = false;
	boolean flagimeis=false;

	// Handler
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				mDialog.cancel();
				Toast.makeText(getApplicationContext(), "登录成功！",
						Toast.LENGTH_SHORT).show();
				SharedPreferenceUtil.storeUserInfo(mContext, name, account, imeis);
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this, MainTabActivity.class);
				startActivity(intent);
				finish();
				break;
			case 1:
				mDialog.cancel();
				Toast.makeText(getApplicationContext(), "无此用户帐号！",
						Toast.LENGTH_SHORT).show();
				break;
			case 2:
				mDialog.cancel();
				Toast.makeText(getApplicationContext(), "工号输入错误！",
						Toast.LENGTH_SHORT).show();
				break;
			case 3:
				mDialog.cancel();
				Toast.makeText(getApplicationContext(), "网络连接超时！",
						Toast.LENGTH_SHORT).show();
				break;
			case 4:
				mDialog.cancel();
				Toast.makeText(getApplicationContext(), "绑定用户失败！",
						Toast.LENGTH_SHORT).show();
				break;
			case 5:
				mDialog.cancel();
				Toast.makeText(getApplicationContext(), "对不起，您的工号已与其他手机绑定！",
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		mContext = getApplicationContext();
		// 初始化数据库
		MyDatabaseUtil.DatabaseInit(LoginActivity.this);
		// 初始化消息推送
		PushAgent mPushAgent = PushAgent.getInstance(this);
		mPushAgent.onAppStart();
		initview();
	}

	// 初始化 同时加载登录监听
	private void initview() {
		edittext1 = (EditText) findViewById(R.id.name);
		edittext2 = (EditText) findViewById(R.id.number);
		TelephonyManager telephonyManager = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);
		imeis = telephonyManager.getDeviceId();

		Button loginBtn = (Button) findViewById(R.id.login);
		loginBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				 login();
				// loginforyun();
//				loginforyun2();
			}

		});

		if (android.os.Build.VERSION.SDK_INT < 18) {
			TextView loginInfo = (TextView) findViewById(R.id.login_tips);
			loginInfo.setText("对不起，您的手机不支持蓝牙BLE服务\n请使用Android4.3或以上设备，谢谢");
			// loginInfo.setTextColor(Color.RED);
			// loginBtn.setEnabled(false);
		}
	}

	private void loginforyun2() {

		System.out.println("blueberry_login_begin");
		name = edittext1.getText().toString().trim();
		account = edittext2.getText().toString().trim();
		System.out.println("blueberry_name="+name);
		CheckNetworkState();
		if (null == imeis) {
			Toast.makeText(LoginActivity.this, "亲，此手机IMEI无效，无法绑定用户！",
					Toast.LENGTH_SHORT).show();
			return;
		}
		if (account.equals("") || name.equals("")) {
			Toast.makeText(LoginActivity.this, "亲，姓名工号不能为空！",
					Toast.LENGTH_SHORT).show();
			return;
		}

		System.out.println("blueberry_判断imei是否已经绑定开始");
		BmobQuery<Users> query = new BmobQuery<Users>();
		query.addWhereEqualTo("imei", imeis);
		query.findObjects(this, new FindListener<Users>() {

			@Override
			public void onError(int code, String msg) {
				System.out.println("blueberry_query_imei_fail");
			}

			@Override
			public void onSuccess(List<Users> listuser) {
				System.out.println("blueberry_querryimei_success");
				System.out.println("blueberry_listuser="+listuser);
				System.out.println("blueberry_listuser.size="+listuser.size());
				
				if (listuser != null && listuser.size() > 0) {
					String imeies=listuser.get(0).getImei();
					if(imeies.equals(imeis)){ //当前手机
						flagimeis=true;
					}
					flagimei = true; 
				}
			}
		});

		System.out.println("blueberry_account_vidile");
		BmobQuery<Users> querys = new BmobQuery<Users>();
		querys.addWhereEqualTo("username", name);
		querys.findObjects(this, new FindListener<Users>() {

			@Override
			public void onSuccess(List<Users> list) {
				System.out.println("blueberry_list.size=" + list.size());
				String accountfromyun = null;
				String imei = null;
				String id = null;
				if (list != null && list.size() != 0) {
					accountfromyun = list.get(0).getAccount().toString();
					imei = list.get(0).getImei();
					id = list.get(0).getObjectId().toString();
					if (accountfromyun != null
							&& !accountfromyun.equals(account)) {
						BaseActivity.ShowToast("输入用户名或密码错误！");
					} else {
						if (imei != null && !imei.equals("")
								&& !imei.equals(imeis)) {
							BaseActivity.ShowToast("对不起，您的工号已与其他手机绑定！");
						} else if (flagimei && !flagimeis) {
							BaseActivity.ShowToast("对不起，您的手机已与其他工号绑定！");
						} else {
							BaseActivity.ShowToast("登录成功！");
							//System.out.println("blueberry_2=" + (imei == null));

							final Users user = new Users();
							user.setUsername(name);
							user.setPassword("5555");
							user.login(LoginActivity.this, new SaveListener() {

								@Override
								public void onSuccess() {
									Users u = user.getCurrentUser(mContext,
											Users.class);
									System.out.println("blueberry_u=" + u);

									if (u != null) {
										if (u.getImei() == null
												|| u.getImei().equals("")) {
											u.setImei(imeis);
											u.update(LoginActivity.this,
													new UpdateListener() {
														@Override
														public void onSuccess() {
															System.out
																	.println("blueberry_添加imei success");
															SharedPreferenceUtil
																	.storeUserInfo(
																			LoginActivity.this,
																			name,
																			account,
																			imeis);
															Intent intent = new Intent();
															intent.setClass(
																	LoginActivity.this,
																	MainTabActivity.class);
															startActivity(intent);
															finish();
														}

														@Override
														public void onFailure(
																int code,
																String msg) {
															System.out
																	.println("blueberry_添加imei fail");
														}
													});
										} else {
											SharedPreferenceUtil.storeUserInfo(
													LoginActivity.this, name,
													account, imeis);
											Intent intent = new Intent();
											intent.setClass(LoginActivity.this,
													MainTabActivity.class);
											startActivity(intent);
											finish();
										}
									}
								}

								@Override
								public void onFailure(int code, String msg) {
									System.out
											.println("blueberry_user.login_fail");
								}
							});

						}
					}
				}
			}

			@Override
			public void onError(int code, String msg) {
				BaseActivity.ShowToast("服务器异常，请稍候！");
			}
		});

	}

	private void loginforyun() {
		System.out.println("blueberry_login_begin");
		name = edittext1.getText().toString().trim(); // 姓名
		account = edittext2.getText().toString().trim(); // 工号
		// 检查网络
		CheckNetworkState();
		if (null == imeis) {
			Toast.makeText(LoginActivity.this, "亲，此手机IMEI无效，无法绑定用户！",
					Toast.LENGTH_SHORT).show();
			return;
		}
		if (account.equals("") || name.equals("")) {
			Toast.makeText(LoginActivity.this, "亲，姓名工号不能为空！",
					Toast.LENGTH_SHORT).show();
			return;
		}

		final Users user = new Users();
		user.setUsername(name);
		user.setAccount(account);
		user.login(this, new SaveListener() {

			@Override
			public void onSuccess() {
				Users myUser = user.getCurrentUser(mContext, Users.class);
				String imeifromTable = myUser.getImei().trim();
				System.out.println("blueberry_imeiformtable=" + imeifromTable);
				if (imeifromTable != null && !imeifromTable.equals("")
						&& !imeifromTable.equals(imeis)) {
					Toast.makeText(LoginActivity.this, "对不起，您的工号已与其他手机绑定！",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(LoginActivity.this, "登录成功",
							Toast.LENGTH_SHORT).show();
					final Users u = user.getCurrentUser(mContext, Users.class);
					if (user != null) {
						user.setImei(imeis);
						user.update(LoginActivity.this, new UpdateListener() {
							@Override
							public void onSuccess() {
								SharedPreferenceUtil.storeUserInfo(LoginActivity.this,
										name, account, imeis);
								Intent intent = new Intent();
								intent.setClass(LoginActivity.this,
										MainTabActivity.class);
								startActivity(intent);
								finish();
							}

							@Override
							public void onFailure(int code, String msg) {

							}
						});
					}
				}

			}

			@Override
			public void onFailure(int code, String msg) {
				Toast.makeText(LoginActivity.this, "输入用户名或密码错误！",
						Toast.LENGTH_SHORT).show();
			}
		});

	}

	private void testFirstIMEI(String username) {
		BmobQuery<Users> query = new BmobQuery<Users>();
		query.addWhereEqualTo("username", username);
		query.findObjects(LoginActivity.this, new FindListener<Users>() {

			@Override
			public void onError(int code, String msg) {
				Toast.makeText(LoginActivity.this, "抱歉，网络加载失败",
						Toast.LENGTH_SHORT).show();
				flagtest = false;
			}

			@Override
			public void onSuccess(List<Users> list) {
				if (list.size() == 1) {
					String imeifromTable = list.get(0).getImei();
					if (imeifromTable != null && !imeifromTable.equals(imeis)) {
						Toast.makeText(LoginActivity.this, "对不起，您的工号已与其他手机绑定！",
								Toast.LENGTH_SHORT).show();
						flagtest = false;
					}
				}
			}
		});
	}

	protected void login() {
		System.out.println("blueberry_login_begin");
		name = edittext1.getText().toString().trim();
		account = edittext2.getText().toString().trim();

		// 添加admin调试入口
		if (name.equals("admin") && account.equals("5555")) {
			Toast.makeText(getApplicationContext(), "登录成功！", Toast.LENGTH_SHORT)
					.show();
			SharedPreferenceUtil.storeUserInfo(mContext, name, account, imeis);
			Intent intent = new Intent();
			intent.setClass(LoginActivity.this, MainTabActivity.class);
			startActivity(intent);
			finish();
		}
		// 检查网络
		CheckNetworkState();
		if (null == imeis) {
			Toast.makeText(LoginActivity.this, "亲，此手机IMEI无效，无法绑定用户！",
					Toast.LENGTH_SHORT).show();
			return;
		}
		if (account.equals("") || name.equals("")) {
			Toast.makeText(LoginActivity.this, "亲，姓名工号不能为空！",
					Toast.LENGTH_SHORT).show();
			return;
		}

		if (!account.equals("") && !name.equals("") && imeis != null) {
			mDialog = new ProgressDialog(LoginActivity.this);
			mDialog.setTitle("登录");
			mDialog.setMessage("正在登录服务器，请稍后...");
			mDialog.show();
			Thread loginThread = new Thread(new LoginThread());
			loginThread.start();
		}
	}

	private JSONObject sendContent(String account, String name)
			throws JSONException, Exception {
		System.out.println("blueberry_sendContent");
		// 使用Map封装请求参数
		Map<String, String> map = new HashMap<String, String>();
		map.put("account", account);
		map.put("name", name);
		map.put("imei", imeis);
		// 定义发送请求的URL http://10.10.2.47:8080/WebProject/LoginServlet
		String url = getResources().getString(R.string.http_ip)
				+ getResources().getString(R.string.login_url);
		String postString = HttpClientUtil.postRequest(url, map);
		System.out.println("blueberry_HttpClientUtil.postRequest(url, map)="
				+ postString);
		if (postString != null) {
			// 发送请求
			return new JSONObject(postString);
		} else {
			return null;
		}

	}

	// LoginThread线程类执行 登录操作
	class LoginThread implements Runnable {
		@Override
		public void run() {
			JSONObject jsonobject;
			String response = null;
			try {
				System.out.println("blueberry_loginthread_begin");
				jsonobject = sendContent(account, name);
				System.out.println("blueberry_jsonobject=" + jsonobject);
				if (null != jsonobject) {
					response = jsonobject.getString("response");
					Message msg = handler.obtainMessage();
					if (response.equals("success")) {
						msg.what = 0;
						handler.sendMessage(msg);
					} else if (response.equals("fail1")) {
						msg.what = 1;
						handler.sendMessage(msg);
					} else if (response.equals("fail2")) {
						msg.what = 2;
						handler.sendMessage(msg);
					} else if (response.equals("fail3")) {
						msg.what = 4;
						handler.sendMessage(msg);
					} else if (response.equals("fail4")) {
						msg.what = 5;
						handler.sendMessage(msg);
					}
				} else {
					Message msg = handler.obtainMessage();
					msg.what = 3;
					handler.sendMessage(msg);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 检查网络状态
	public void CheckNetworkState() {
		boolean flag = false;
		ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		State mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		// 如果3G、wifi、2G等网络状态是连接的，则退出，否则显示提示信息进入网络设置界面
		if (mobile == State.CONNECTED || mobile == State.CONNECTING)
			return;
		if (wifi == State.CONNECTED || wifi == State.CONNECTING)
			return;
		showTips();
	}

	private void showTips() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle("没有可用网络");
		builder.setMessage("当前网络不可用，是否设置网络？");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// 如果没有网络连接，则进入网络设置界面
				startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		builder.create();
		builder.show();
	}

}
